package com.nulp.psycho.db.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.nulp.psycho.db.ConnectionManager;
import com.nulp.psycho.db.dao.BaseDao;
import com.nulp.psycho.db.mapping.Converter;
import com.nulp.psycho.db.model.Group;

public class GroupDao implements BaseDao{

	
	private final String ADD_GROUP = "INSERT INTO groups (user_id, password, name) VALUES (?,?,?)";
	private final String GET_GROUP_BY_ID = "SELECT * FROM groups WHERE id = ?";
	private final String REMOVE_GROUP = "DELETE FROM groups WHERE id = ?";
	private final String UPDATE_GROUP = "UPDATE groups SET user_id=?, password=?, name=? WHERE id = ?";
	
	
	@Override
	public <T> void create(T element) {
		Group temp = (Group) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(ADD_GROUP)) {
			preparedStatement.setInt(1, temp.getUserId());
			preparedStatement.setString(2, temp.getPassword());
			preparedStatement.setString(3, temp.getName());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T read(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		Group group = null;
		try (PreparedStatement statement = connection
				.prepareStatement(GET_GROUP_BY_ID)) {
			statement.setInt(1, id);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				group = Converter.<Group> fromResaultSetToObject(rs,
						Group.class);
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) group;	
	}

	@Override
	public void delete(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(REMOVE_GROUP)) {
			preparedStatement.setInt(1, id);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}

	@Override
	public <T> void update(T element) {
		Group temp = (Group) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(UPDATE_GROUP)) {
			preparedStatement.setInt(4, temp.getId());
			preparedStatement.setInt(1, temp.getUserId());
			preparedStatement.setString(2, temp.getPassword());
			preparedStatement.setString(3, temp.getName());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}
	
}
